package com.daiziru.wuyanmall.controller;

import com.daiziru.wuyanmall.config.MyPayConfig;
import com.daiziru.wuyanmall.dao.OrdersMapper;
import com.daiziru.wuyanmall.entity.Orders;
import com.daiziru.wuyanmall.service.OrderService;
import com.daiziru.wuyanmall.service.impl.OrderServiceImpl;
import com.daiziru.wuyanmall.vo.ResultStatus;
import com.daiziru.wuyanmall.vo.ResultVO;
import com.github.wxpay.sdk.WXPay;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：無言
 * 时间：2022/3/19 16:44
 * 描述：永无BUG
 */

@CrossOrigin
@RestController
@RequestMapping("/order")
@Api(value = "提供订单的相关的操作接口", tags = "订单管理")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderServiceImpl orderServiceImpl;

    @Autowired
    private OrdersMapper ordersMapper;

    //日志配置
    private Logger logger = LoggerFactory.getLogger(OrderController.class);

    @PostMapping("/add")
    public ResultVO add(String cids, @RequestBody Orders order){
        ResultVO resultVO = null;
        try {
            Map<String, String> orderInfo = orderService.addOrder(cids, order);
            if(orderInfo!=null){
                String orderId = orderInfo.get("orderId");
                //设置当前订单信息
                HashMap<String,String> data = new HashMap<>();
                data.put("body",orderInfo.get("productNames"));  //商品描述
                data.put("out_trade_no",orderId);               //使用当前用户订单的编号作为当前支付交易的交易号
                data.put("fee_type","CNY");                     //支付币种
                //data.put("total_fee",order.getActualAmount()*100+"");          //支付金额
                data.put("total_fee","1");
                data.put("trade_type","NATIVE");                //交易类型
                data.put("notify_url","http://114.55.73.21:8080/pay/callback");  //回调链接，使用了内网穿透         //设置支付完成时的回调方法接口

                //发送请求，获取响应
                //微信支付：申请支付连接
                WXPay wxPay = new WXPay(new MyPayConfig());
                Map<String, String> resp = wxPay.unifiedOrder(data);
                orderInfo.put("payUrl",resp.get("code_url"));
                //orderInfo中包含：订单编号，购买的商品名称，支付链接
                resultVO = new ResultVO(ResultStatus.OK,"提交订单成功！",orderInfo);
            }else{
                resultVO = new ResultVO(ResultStatus.NO,"提交订单失败！",null);
            }
        } catch (SQLException e) {
            resultVO = new ResultVO(ResultStatus.NO,"提交订单失败！",null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultVO;
    }

    @GetMapping("/status/{oid}")
    public ResultVO getOrderStatus(@PathVariable("oid") String orderId, @RequestHeader("token") String token){
        ResultVO resultVO = orderService.getOrderById(orderId);
        return resultVO;
    }


    @GetMapping("/listOrders")
    @ApiOperation("订单查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String",name = "userId", value = "用户id",required = true),
            @ApiImplicitParam(dataType = "String",name = "status", value = "订单状态",required = false),
            @ApiImplicitParam(dataType = "int",name = "pageNum", value = "当前页码",required = true),
            @ApiImplicitParam(dataType = "int",name = "limit", value = "每页显示条数",required = true)
    })
    public ResultVO list( @RequestHeader("token") String token,
                          String userId, String status, int pageNum, int limit){
        ResultVO resultVO = orderService.listOrders(userId, status, pageNum, limit);
        return resultVO;
    }

    @PostMapping("/closeOrder")
    @ApiOperation("关闭订单接口")
    public ResultVO closerOrder(String orderId){
        orderServiceImpl.closeOrder(orderId);
        //根据订单查询订单的状态是否改为6
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        List<Orders> orders = ordersMapper.selectByExample(example);
        System.out.println(orders);

        if(orders != null){
            String status = orders.get(0).getStatus();
            if(status.equals("6")){
                return new ResultVO(ResultStatus.OK,"success", orders.get(0));
            }
        }
        return new ResultVO(ResultStatus.NO,"fail", null);

    };


    @PostMapping("/addWaitPayOrder")
    @ApiOperation("增加未支付订单链接接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String",name = "orderId", value = "订单id",required = true),
            @ApiImplicitParam(dataType = "String",name = "payUrl", value = "订单支付链接",required = false),
    })
    public ResultVO addWaitPayOrder(String orderId, String payUrl){
        ResultVO resultVO = orderService.addWaitPayOrder(orderId, payUrl);
        return resultVO;
    };

    @GetMapping("/selectPayUrl")
    @ApiOperation("查询未订单支付链接接口")
    public ResultVO selectPayUrl(String orderId){
        ResultVO resultVO = orderService.selectWaitPayOrderId(orderId);
        return resultVO;
    };

    @GetMapping("/selectOrderTotalAmount")
    @ApiOperation("查询订单总价格接口")
    public ResultVO getOrderTotalAmount(String orderId, @RequestHeader("token") String token){
        ResultVO resultVO = orderService.getOrderTotalAmountById(orderId);
        return resultVO;
    }

    @DeleteMapping("/deleteOrder")
    @ApiOperation("删除订单接口")
    public ResultVO deleteOrderByOrderId(String orderId){
        ResultVO resultVO = orderService.deleteOrderByOrderId(orderId);
        return resultVO;
    }

    @PutMapping("/updateStatus")
    @ApiOperation("修改订单状态接口")
    public ResultVO updateOrderStatusByOrderId(String orderId, String status){
        int i = orderService.updateOrderStatus(orderId, status);
        return new ResultVO(ResultStatus.OK, "success", 1);
    }



}

